
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;;
import cn.hutool.http.HttpRequest;
import com.smdk.dsminio.vo.MultipartFileParam;
import java.io.File;
import java.io.FileInputStream;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
 
public class FileUploadRunnable implements Runnable {

 
    //文件id
    private String fileId;
 
    //分块编号
    private int num;
    //发枪器 文件分割完毕准备上传
    private CountDownLatch countDownLatch;
    
   //当前分段大小
    private Long partSize;
 
    //当前分段在输入流中的起始位置
    private Long partStart;
    //总分片
    private Long partCount;
   //总文件
    private File file;
    //文件MD5
    private String fileMd5;
    public  FileUploadRunnable(String fileId, int num, CountDownLatch countDownLatch, File file, Long partSize,Long partStart,Long partCount,String fileMd5){
        this.fileId=fileId;
        this.num=num;
        this.countDownLatch=countDownLatch;
        this.partSize=partSize;
        this.partStart =partStart;
        this.file =file;
        this.partCount=partCount;
        this.fileMd5=fileMd5;
    }

    @Override
    public  void run() {
        try{
            FileInputStream fis = new FileInputStream(file);
            MultipartFileParam multipartFileParam =new MultipartFileParam();
            //丢弃起始位置 读过的直接可以不要了 免得浪费资源
            fis.skip(partStart);
            byte[] fileByte=new byte[partSize.intValue()];
            //必须判断read有可能读不到
            while (fis.read(fileByte,0,partSize.intValue())!=-1){
                multipartFileParam.setFileBaseStr(Base64.encode(fileByte));
                multipartFileParam.setBucketId(1L);
                multipartFileParam.setChunk(num);
                multipartFileParam.setChunks(partCount.intValue());
                multipartFileParam.setParentFolderId(1L);
                multipartFileParam.setSize(file.length());
                multipartFileParam.setUid(fileId);
                multipartFileParam.setId("0");
                multipartFileParam.setMd5(fileMd5);
                multipartFileParam.setFileName(file.getName());
                Map paramMap= BeanUtil.beanToMap(multipartFileParam);
                System.out.println("开始上传分块:"+num);
                //Gateway网关
                String response = HttpRequest.post("http://w2pb2wgp7ebe6x1:9008/api-a/api/fileNodeDistribute").form(paramMap).timeout(5000).execute().body();
                System.out.println(response);
                System.out.println("分块"+num+"上传完毕");
            }
            countDownLatch.countDown();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}